package me.shurufa.activities;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import me.shurufa.R;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.widget.MaskSurfaceView;
import me.shurufa.widget.colordialog.ColorDialog;
import me.shurufa.widget.colordialog.PromptDialog;

/**
 * 摘书启动页面 相机surfaceView
 *
 * @FileName: me.shurufa.activities.CameraActivity.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-18 11:39
 */
public class CameraActivity extends BaseActivity implements View.OnClickListener, SurfaceHolder.Callback, Camera.PictureCallback, Camera.ShutterCallback {

    @Bind(R.id.sfc_preview)
    SurfaceView sfcPreview;
    @Bind(R.id.btn_write)
    ImageButton btnWrite;
    @Bind(R.id.btn_shutter)
    Button btnShutter;
    @Bind(R.id.btn_flash)
    Button btnFlash;
    @Bind(R.id.camera_back)
    ImageView cameraBack;

    MaskSurfaceView maskSurfaceView;

    /** 睡眠时间 */
    protected static final long SLEEP_TIME = 50;
    /** 初始化相机 */
    protected static final int MSG_ID_CAMERA_START = 0x01;
    /** 释放相机资源 */
    protected static final int MSG_ID_CAMERA_STOP = 0x2;

    boolean mIsActivityTeady = false;
    boolean mIsSurfaceTeady = false;
    SurfaceHolder mHolder;

    Camera.Parameters mParameters;
    Camera mCamera;
    /** 支持的闪光灯模式 */
    List<String> mSupportFlash;
    int mIndexFlash;
    WindowManager wm;
    int width,height;
    private long bookId;
    private boolean isKnowBookId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_camera;
        super.onCreate(savedInstanceState);
        wm = this.getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        bookId = getIntent().getLongExtra(Constants.ARG_BOOK_ID,0);
        if (bookId!=0)
            isKnowBookId = true;
        uiInit();
    }

    private void uiInit() {
        cameraBack.setOnClickListener(this);
        btnWrite.setOnClickListener(this);
        btnShutter.setOnClickListener(this);
        btnFlash.setOnClickListener(this);
        sfcPreview.getHolder().addCallback(this);
        sfcPreview.setOnClickListener(this);
        mHolder = sfcPreview.getHolder();
        maskSurfaceView = (MaskSurfaceView)findViewById(R.id.mask_view);
        LogUtils.kLog().d("width-100="+(width-100)+",height/4="+height/4);
        maskSurfaceView.setMaskSize(width*5/6,height/3);
    }

    /**
     * 相机为SurfaceView 要跟随生命周期
     */
    @Override
    protected void onStart() {
        super.onStart();
        mIsActivityTeady = true;
        mHandler.sendEmptyMessage(MSG_ID_CAMERA_START);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.btn_flash:
                int index = (mIndexFlash + 1) % mSupportFlash.size();
                String mode = mSupportFlash.get(index);
                // 将新的闪光灯模式设置到参数中
                mParameters.setFlashMode(mode);
                // 设置参数到照相机上
                mCamera.setParameters(mParameters);
                refreshFlashMode();
//                intent = new Intent(CameraActivity.this,QRScanActivity.class);
//                intent.putExtra(Constants.EXTRA_FROM_CAMERA,true);
//                startActivity(intent);
//                finish();
                break;
            case R.id.btn_shutter:
                /*
				 * shutter:快门回调，在按下快门的瞬间会调用此接口中的方法， 常用于播放自定义的快门
				 * raw：照片回调，将未经处理的最原始的照片数据信息传递给此接口
				 * postview：照片回调，将经过一定处理的照片数据信息传递给此接口 此处理一般是经过硬件处理，所以部分手机可能不支持。
				 * jpeq 照片回调 ：将经过较大压缩的照片数据传递给此接口。最常用的接口
				 */
                mCamera.takePicture(this, null, null, this);
                break;
            case R.id.btn_write:
                mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
                intent = new Intent(CameraActivity.this,BitmapNoTransformActivity.class);
                if (bookId!=0L) {
                    intent.putExtra(Constants.ARG_BOOK_ID, bookId);
                }
                startActivity(intent);
                finish();
                break;
            case R.id.sfc_preview:
                //调用autoFocus方法可以进行自动对焦
                //参数是个回调，用于确认对焦是否成功，如果无需知道对焦是否成功，设置为null
               // mCamera.autoFocus(null);
                break;
            case R.id.camera_back:
                mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
                finish();
                break;
            default:
                break;
        }

    }
//  SurfaceView callback method start---->
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Canvas canvas = mHolder.lockCanvas();
        canvas.drawColor(Color.BLACK);
        mHolder.unlockCanvasAndPost(canvas);
        mIsSurfaceTeady = true;
        mHandler.sendEmptyMessage(MSG_ID_CAMERA_START);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera=null;
        mIsSurfaceTeady = false;
        mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
    }
//    SurfaceView callback method end --->
//    Camera implements method callback  start----->

    /**
     * @param data
     *            字节数组，包含照片的数据
     * @param camera
     *            刚进行拍照的相机
     * */
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        FileOutputStream fos = null;
        // 用于创建临时文件
        try {
            mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);

//
            Bitmap bitmap = cutImage(data);
//
            File file = File.createTempFile("DCIM", ".tmp");
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            Intent intent = new Intent(this, BitmapTransformActivity.class);
            intent.putExtra(Constants.EXTRA_CAMERA_PHOTO, file.getAbsolutePath());
            if (bookId!=0L) {
                intent.putExtra(Constants.ARG_BOOK_ID, bookId);
            }
            startActivity(intent);
            finish();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Bitmap cutImage(byte[] data){
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

            Matrix matrix = new Matrix();
            matrix.reset();
            matrix.setRotate(90);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap = Bitmap.createScaledBitmap(bitmap,width,height,true);

        if(maskSurfaceView == null){
            return bitmap;
        }else{
            int[] sizes = maskSurfaceView.getMaskSize();
            if(sizes[0]==0 || sizes[1]==0){
                return bitmap;
            }
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            int x = (w-sizes[0])/2;
            int y = (h-sizes[1])/2;
            return Bitmap.createBitmap(bitmap, x, y,sizes[0], sizes[1]);
        }
    }

    /**
     * 快门按下回调
     */
    @Override
    public void onShutter() {

    }
//    Camera implements method callback end------>

    int showDialogTimes;
    private void startCamera() {
        // 如果相机在短时间内重复打开，先关闭一下就不会出错了；
        stopCamera();
        // 可以得到摄像头的个数；此方法的返回值-1是Open方法的最大值；
        // Camera.getNumberOfCameras();
        // 不带参数 打开默认摄像头；如果带int参数表示打开指定的摄像头
        // 一般0表示的后置摄像头，1表示前置后置摄像头
        LogUtils.kLog().e("Camera.getNumberOfCameras:"+mCamera.getNumberOfCameras());
        try {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        }catch (Exception e){
            showDialogTimes++;
            if (!(showDialogTimes==1))
                showAlertDialog();
            else
                showDialogTimes=0;
        }



    if(mCamera!=null){
        mCamera.setDisplayOrientation(90);
        mParameters = mCamera.getParameters();
        //自动对焦
        mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        //获取支持的闪光灯模式
        mSupportFlash = mParameters.getSupportedFlashModes();
//adapteration
        List<Camera.Size> supportedPreviewSizes = mParameters.getSupportedPreviewSizes();

        Camera.Size previewSize = getOptimalPreviewSize(supportedPreviewSizes,width,height);
        mParameters.setPreviewSize(previewSize.width, previewSize.height);
        List<Camera.Size> supportedPictureSizes = mParameters.getSupportedPictureSizes();
        Camera.Size pictureSize = getOptimalPreviewSize(supportedPictureSizes,width,height);
        mParameters.setPictureSize(pictureSize.width, pictureSize.height);
        mCamera.setParameters(mParameters);
//
        mSupportFlash = mParameters.getSupportedFlashModes();
        refreshFlashMode();
        try {
            mCamera.setPreviewDisplay(mHolder);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        // 开始捕获图像进行预览
        mCamera.startPreview();
        }
    }

    private void showAlertDialog() {
//        final Dialog lDialog = new Dialog(this,R.style.dialog_style);
//        lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        lDialog.setContentView(R.layout.r_okcanceldialogview);
//        TextView txtMsg = (TextView) lDialog.findViewById(R.id.dialog_message);
//        TextView txtTitle = (TextView)lDialog.findViewById(R.id.dialog_title);
//        txtMsg.setText(getString(R.string.camera_permission));
//        ((Button) lDialog.findViewById(R.id.ok))
//                .setOnClickListener(new View.OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        lDialog.dismiss();
//                        CameraActivity.this.finish();
//                    }
//                });
//        lDialog.show();
        new PromptDialog(this).setDialogType(PromptDialog.DIALOG_TYPE_WRONG)
                .setTitleText(getString(R.string.permission_decline)).setContentText(getString(R.string.camera_permission))
                .setPositiveListener(getString(R.string.i_know), new PromptDialog.OnPositiveListener() {
                    @Override
                    public void onClick(PromptDialog dialog) {
                        dialog.dismiss();
                        mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
                        CameraActivity.this.finish();
                    }
                }).show();

    }

    /** 刷新闪光灯按钮上的图片状态 */
    private void refreshFlashMode() {
        // 得到当前的闪光灯状态
        String mode = mParameters.getFlashMode();
        // 得到当前闪光灯模式在列表中的下标；
        mIndexFlash = mSupportFlash.indexOf(mode);
        LogUtils.kLog().e(mode);
        if ("off".equals(mode)) {
            btnFlash.setText("off");
        } else if ("on".equals(mode)) {
            btnFlash.setText("on");
        } else if ("auto".equals(mode)) {
            btnFlash.setText("auto");
        } else if ("torch".equals(mode)){
            btnFlash.setText("torch");
        }
    }

    private void stopCamera() {

        if (mCamera != null) {
            // 停止预览
            mCamera.stopPreview();
            // 释放相机资源
            mCamera.release();
        }
        mCamera = null;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_ID_CAMERA_START: {
                    if (mIsActivityTeady && mIsSurfaceTeady) {
                        startCamera();
                    } else if (mIsActivityTeady || mIsSurfaceTeady) {
                        // 移除其他正在等待的消息，即同时只能有一个消息在等待；
                        removeMessages(MSG_ID_CAMERA_START);
                        sendEmptyMessageDelayed(MSG_ID_CAMERA_START, SLEEP_TIME);
                    }
                    break;
                }

                case MSG_ID_CAMERA_STOP: {
                    removeMessages(MSG_ID_CAMERA_START);
                    removeMessages(MSG_ID_CAMERA_STOP);
                    stopCamera();
                    break;
                }
                default:
                    break;
            }
        }

    };
//获取最佳尺寸方法一 [变形]
//    private int getPictureSize(List<Camera.Size> sizes) {
//        WindowManager wm = this.getWindowManager();
//        int screenWidth = wm.getDefaultDisplay().getWidth();
//// 屏幕的宽度
//        int index = -1;
//        for (int i = 0; i < sizes.size(); i++) {
//            if (Math.abs(screenWidth - sizes.get(i).width) == 0) {
//                index = i;
//                break;
//            }
//        }
//// 当未找到与手机分辨率相等的数值,取列表中间的分辨率
//        if (index == -1) {
//            index = sizes.size() / 2;
//        }
//        return index;
//    }
//获取最佳尺寸方法二
    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int width, int height) {
        final double ASPECT_TOLERANCE = 0.05;
        double targetRatio = (double) width / height;
        if (sizes == null)
            return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = height;

        // Try to find an size match aspect ratio and size
        for (Camera.Size size : sizes) {
            double r = size.width*1.0/size.height*1.0;
            if(r!=4/3 || r!=3/4 || r!=16/9 || r!=9/16){
                continue;
            }

            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
            finish();
        }
        return false;
    }
}
